package com.ruoyi.system.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.YhMp;
import com.ruoyi.common.core.domain.entity.YhMember;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.YhMemberLevelRule;
import com.ruoyi.system.domain.vo.MemberLevelVo;
import com.ruoyi.system.mapper.YhMpMapper;
import com.ruoyi.system.domain.YhPointRecord;
import com.ruoyi.system.mapper.YhMemberMapper;
import com.ruoyi.system.service.IYhMemberLevelRuleService;
import com.ruoyi.system.service.IYhMemberService;
import com.ruoyi.system.service.IYhPointRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;


/**
 * 用户Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-06-06
 */
@Service
public class YhMemberServiceImpl extends ServiceImpl<YhMemberMapper, YhMember> implements IYhMemberService
{
    @Autowired
    private YhMpMapper yhMpMapper;

    @Autowired
    private IYhPointRecordService pointRecordService;

    @Autowired
    private IYhMemberLevelRuleService memberLevelRuleService;

    @Override
    public void getShareQRCode(HttpServletResponse response) throws Exception {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        YhMember yhMember = getById(loginUser.getUserId());

        if(yhMember.getMemberLevel() < 2)
            throw new ServiceException("当前会员等级没有权限分享！");

        response.setContentType("image/gif");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        String accessToken = getAccessToken();

        //文档地址 https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html#%E8%AF%B7%E6%B1%82%E5%8F%82%E6%95%B0

        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;

        // 发送请求参数
        JSONObject paramJson = new JSONObject();
        paramJson.set("page", "pages/tabBar/home/home");
        paramJson.set("check_path", false);
        paramJson.set("width", 280);
        paramJson.set("scene", loginUser.getUserId());
        //设置小程序码版本
        //paramJson.set("env_version","release"); 默认正式
        paramJson.set("env_version","trial"); //体验版
//        paramJson.set("env_version","develop"); //开发版

        InputStream inputStream = HttpUtils.postInputStream(url, paramJson);

        //将流写出到response
        IoUtil.copy(inputStream, response.getOutputStream());
    }

    @Transactional
    @Override
    public boolean addMemberPoint(String memberId, Double point, String associationId, String type) {
        // 添加积分记录
        YhPointRecord yhPointRecord = new YhPointRecord(memberId, point, associationId, type);
        pointRecordService.save(yhPointRecord);

        // 增加用户积分
        YhMember yhMember = this.getById(memberId);
        Double yhMemberPoint = yhMember.getPoint() == null ? 0 : yhMember.getPoint();

        YhMember newMember = new YhMember();
        newMember.setId(memberId);
        newMember.setPoint(Double.sum(yhMemberPoint, point));
        return this.updateById(newMember);
    }

    @Override
    public MemberLevelVo memberLevel() {
        YhMember yhMember = getById(SecurityUtils.getUserId());
        YhMemberLevelRule memberLevelRule = memberLevelRuleService.getOne(new LambdaQueryWrapper<YhMemberLevelRule>()
                .eq(YhMemberLevelRule::getMemberLevel, yhMember.getMemberLevel()));

        YhMemberLevelRule nextMemberLevelRule = memberLevelRuleService.getOne(new LambdaQueryWrapper<YhMemberLevelRule>()
                .eq(YhMemberLevelRule::getMemberLevel, yhMember.getMemberLevel() + 1));
        MemberLevelVo vo = new MemberLevelVo();

        vo.setCommissionRate(memberLevelRule.getCommissionRate());
        if(StringUtils.isNotNull(nextMemberLevelRule)){
            vo.setNextPrice(nextMemberLevelRule.getPrice());
            vo.setNextCommissionRate(nextMemberLevelRule.getCommissionRate());
            vo.setNextMemberLeverId(nextMemberLevelRule.getId());
        }
        return vo;
    }

    @Override
    public List<YhMember> listByAdmin(YhMember yhMember) {
        return yhMpMapper.listByAdmin(yhMember.queryWrapper());
    }


    public String getAccessToken(){
        YhMp yhMpSetting = yhMpMapper.getYhMpSetting();
        String appid = yhMpSetting.getAppId();
        String secret = yhMpSetting.getAppSecret();
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
        String result = HttpUtil.get(url);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        return jsonObject.get("access_token").toString();
    }
}
